﻿using System;
using System.Security.Principal;
using System.Collections.Generic;
using WeBlog.Models;

public static class SecurityExtensions {
    public static bool IsAdmin(this IPrincipal user){
        return user.IsInRole(Role.Admin);
    }

    public static bool IsEditor(this IPrincipal user)
    {
        return user.IsInRole(Role.Editor);
    }

    public static bool IsAuthor(this IPrincipal user)
    {
        return user.IsInRole(Role.Author);
    }

    public static bool IsSubscriber(this IPrincipal user)
    {
        return user.IsInRole(Role.Subscriber);
    }

    public static bool IsContributor(this IPrincipal user)
    {
        return user.IsInRole(Role.Contributor);
    }

    public static bool CanCreatePost(this IPrincipal user) {
        return (user.IsAdmin() || user.IsEditor() || user.IsAuthor());
    }

    public static bool CanManagePosts(this IPrincipal user)
    {
        return (user.IsAdmin() || user.IsEditor() || user.IsAuthor());
    }

    public static bool CanEditPost(this IPrincipal user, Post post) {
        if (user.IsAdmin() || user.IsEditor())
            return true;
        else if (user.IsAuthor())
            return (user.Identity.Name == post.Author.Email);

        return false;
    }

    public static bool CanDeletePost(this IPrincipal user) {
        if (user.IsAdmin() || user.IsEditor())
            return true;

        return false;
    }

    public static string FullName( this IPrincipal user )
    {
        if (System.Web.HttpContext.Current != null)
        {
            if (System.Web.HttpContext.Current.Session != null)
            {
                if (System.Web.HttpContext.Current.Session["User"] != null)
                {                    
                    return ((User)System.Web.HttpContext.Current.Session["User"]).FullName;
                }
            }
        }

        return user.Identity.Name;
    }    

    public static bool InAnyRole(this IPrincipal user, params string[] roles)
    {
        foreach (string role in roles)
        {
            if (user.IsInRole(role)) return true;
        }
        return false;
    }
}